sugarfreeControllers
.controller('LessonController', ['$scope','$log','$http', '$timeout', '$compile', '$filter','$route','$routeParams','$location','HttpService','Utils',"DictionarySerivce",'TIME_GROUP','ClassTypes','TimeService','MESSAGE','QINIU','PageService','$route',
		function($scope,$log,$http, $timeout, $compile, $filter,$route,$routeParams,$location,httpService,Utils,dicSerivce,TIME_GROUP,ClassTypes,timeService,message,QINIU,pageService,$route) {
	
	$scope.createLessonForm = function(){createLessonForm(); $scope.errMsg={};};
	$scope.unCreateLessonForm = function(){unCreateLessonForm(); $scope.errMsg={};};
	$scope.createLesson = function(){createLesson();};
	
	$scope.editLessonForm = function(lessonId){editLessonForm(lessonId);$scope.errMsg={};};
	$scope.unEditLessonForm = function(lessonId){unEditLessonForm(lessonId);$scope.errMsg={};};
	$scope.updateLesson = function(){updateLesson();};
	
	$scope.viewLesson = function(lesson){viewLesson(lesson);};
	$scope.unViewLesson = function(){unViewLesson();};
	
	
	$scope.retrieveLessonSchedule = function(){retrieveLessonSchedule();};
	$scope.copyLessonToNextWeek = function(classType,fromWeek,targetWeek){copyLessonToNextWeek(classType,fromWeek,targetWeek);};
	$scope.checkLesson = function(lesson){lesson.checked = !lesson.checked;};
	$scope.cancelLessons = function(){cancelLessons()};
	$scope.checkAllDay = function(lessonTpl){checkAllDay(lessonTpl)};
	
	$scope.checkNonPublishLessons = function(status){checkNonPublishLessons(status);};
	$scope.checkAllLessons = function(status){checkAllLessons(status);};
	$scope.sendLesson = function(){sendLesson();};
	
	//课程信息管理
	$scope.retrieveCourseByPage = function(){retrieveCourseByPage()};
	$scope.selectAllCourses = function(classType){selectAllCourses(classType);};
	$scope.createCourseForm = function(){createCourseForm();$scope.errMsg={};};
	$scope.unCreateCourseForm = function(){unCreateCourseForm();$scope.errMsg={};};
	$scope.createCourse = function(){createCourse();};
	
	$scope.editCourseForm = function(courseId){editCourseForm(courseId);$scope.errMsg={};};
	$scope.unEditCourseForm = function(){unEditCourseForm();$scope.errMsg={};};
	$scope.updateCourse = function(){updateCourse();};
	
	$scope.deleteCourse = function(){deleteCourse();};
	
	
	$scope.delCourseImage = function(fileId,type){delCourseImage(fileId,type);};
    $scope.delOriginCourseImage = function(index,fileId){delOriginCourseImage(index,fileId);};
	
	
	$scope.signForm = function(){
	  	Utils.setParclose(true);
	  	$scope.page.needSignForm = true;
    }
	
	$scope.closeSignForm = function(){
	  	$scope.errMsg = $scope.errMsg || {};
	  	$scope.errMsg.signMsg = '';
	  	$scope.signCode = '';
	  	$scope.page.needSignForm = false;
	  	Utils.setParclose(false);
	}
	
	$scope.sign = function(){
	  	$scope.errMsg = $scope.errMsg || {};
	  	if(!$scope.signCode){
	  		$scope.errMsg.signMsg = $scope.msg.emptySign;
	  		return ;
	  	}else{
	  		$scope.errMsg.signMsg = "";
	  	}
	  	
	  	var _url = "receipt/sign";
	  	var _dataStr="code=" + $scope.signCode;
	  	Utils.setTopParclose(true);
	  	httpService.post(_url,_dataStr).then(
	  		function(rsps){
	  			console.info("rsps",rsps);
	  			if(rsps.data.errCode === '8000'){
	  				alert('签到成功');
	  				$scope.signCode = '';
	  				$scope.page.needSignForm = false;
		  			Utils.setTopParclose(false);
		  			Utils.setParclose(false);
	  			}else{
	  				Utils.setTopParclose(false);
	  				$scope.errMsg.signMsg = $scope.msg.invalidSign;
	  				//$scope.signCode = "";
	  			}
	  			
	  		},
	  		function(rsps){
	  			alert('签到出现异常');
	  			Utils.setTopParclose(false);
	  			//Utils.setParclose(false);
	  		}
	  	);
	  	
	  }
	
	//TODO 待废除
	//$scope.retrieveLessonTpls = function(classType) {retrieveLessonTpls(classType);};
	//TODO 待废除
	//$scope.createForm = function(){createForm(); $scope.errMsg={};};
	
	//$scope.editLessonForm = function(){editLessonForm(); $scope.errMsg={};};
	//$scope.unEditLessonForm = function(){unEditLessonForm(); $scope.errMsg={};};
	//$scope.unCreateForm = function(){unCreateForm(); $scope.errMsg={};$scope.form.submitted = false;};
	//$scope.unEditForm = function(){unEditForm(); $scope.errMsg={};};
	//$scope.reUnEditForm = function(){reUnEditForm(); $scope.errMsg={};};
	//$scope.unViewForm = function(){unViewForm(); $scope.errMsg={};};
	//$scope.deleteForm = function(){deleteForm(); $scope.errMsg={};};
	//$scope.unDeleteForm = function(){unDeleteForm();$scope.errMsg={};};
	
	$scope.clearFields = function(){clearFields();};
	
	//$scope.editTemplate = function() {editTemplate();};
	

	
	
	$scope.selectTemplate = function($event,lessonTpl_id){selectTemplate($event,lessonTpl_id);};
	
	//deleted
	//$scope.retrieveContracts = function(){retrieveContracts();};
	
	$scope.retrieveCourses = function(classType) {retrieveCourses(classType);};
	
    $scope.checkClassType = function(value){checkClassType(value);};
    
    $scope.cancelledView = function(){cancelledView();};
    
    $scope.tabSwitch = function(classTypeV){tabSwitch(classTypeV);$scope.errMsg={};};
    
    //deleted
    //$scope.checkDirty = function(){checkDirty();};
    
    //$scope.createTemplate = function () {createTemplate();};
    
    //$scope.updateTemplate = function () {updateTemplate();};
    
    //$scope.deleteTemplate = function () {deleteTemplate();};
    
  //////////
	
  // retrieve class schedule
  function retrieveLessonTpls(classType) {
	Utils.setProcessParclose(true);  
    $scope.events = [];
    var _queryLessonTpls = "lesson/template/query?classType=" + classType;
    var _urlLessonTpls = $scope.apiUrl + _queryLessonTpls;
    
    if($scope.log.debug){
    	$log.info("query%sUrl=>","课程表",_urlLessonTpls);
    }
    $timeout(function (){
	    $http.get(_urlLessonTpls).success(function(data) {
			$scope.lessonTpls = data;
			if($scope.log.debug){
				$log.info("'retrieve class schedule:'", _urlLessonTpls, $scope.lessonTpls);
			}
			angular.forEach($scope.lessonTpls, function(item) {
				var beginDate = new Date();
				var endDate = angular.copy(beginDate);
				endDate.setHours(parseInt(item.beginTime.split(':')[0]));
				endDate.setMinutes(parseInt(item.beginTime.split(':')[1]));
				endDate.setMinutes(endDate.getMinutes() + item.duration);
				beginDate.setHours(item.beginTime.split(':')[0]);
				beginDate.setMinutes(item.beginTime.split(':')[1]);
				
				//item.tBeginTime = item.tBeginTime;
				item.endTime = $filter('date')(endDate, 'HH:mm');
				//alert(item.beginTime.split(':')[0]);
				item.hourOfDay = item.beginTime.split(':')[0];
				
				item.tBeginDateTime = beginDate;
				item.tEndDateTime = endDate;
			});
			Utils.setProcessParclose(false);
	    });
	},500);
  }
  
  
  function retrieveLessonSchedule(){
  	$scope.lessonBtnGroup = true;
  	$scope.courseBtnGroup = false;
  	var week = $scope.week;
  	var classType = $scope.classType;
  	Utils.setProcessParclose(true);  
    $scope.events = [];
    var _queryLessonSchedule = "lesson/schedule/query?classType=" + classType +
    						   "&week=" + week;
    if($scope.log.debug){
    	$log.info("query%sUrl=>","课程表",_queryLessonSchedule);
    }
    $timeout(function (){
	    httpService.get(_queryLessonSchedule).then(function(resp) {
	    	try{
				$scope.lessonTpls = resp.data;
				//console.info('##$scope.lessonTpls',$scope.lessonTpls);
				angular.forEach($scope.lessonTpls, function(item) {
					item.tBeginDateTime = item.beginTime.substr(8,2) + ":" + item.beginTime.substr(10);
					item.tEndDateTime = item.endTime.substr(8,2) + ":" + item.endTime.substr(10);
					item.hourOfDay = item.beginTime.substr(8,2);
					item.beginTime = item.beginTime.substr(8,2) + ":" + item.beginTime.substr(10);
					item.endTime = item.endTime.substr(8,2) + ":" + item.endTime.substr(10);
					item.checked = false;
				});
			}catch(e){
				console.error("Error",e);
				alert('查询出错！');
			}finally{
				Utils.setProcessParclose(false);
			}
	    },function(resp){
	    	alert('查询出错！');
	    	Utils.setProcessParclose(false);
	    });
	},500);
  }
  
  
  function copyLessonToNextWeek(classType,fromWeek,targetWeek){
//	console.info('classType',classType);
//	console.info('fromWeek',fromWeek);
//	console.info('targetWeek',targetWeek);
  	var _queryLessonSchedule = "lesson/schedule/query?classType=" + classType;
    var weekParam = "&week=" + fromWeek;
  	httpService.get(_queryLessonSchedule + weekParam).then(function(rsps){
  		var lessons = rsps.data;
  		if(lessons.length > 0){
  			weekParam = "&week=" + targetWeek;
  			httpService.get(_queryLessonSchedule + weekParam).then(function(rsps){
  				lessons = rsps.data;
  				var copyAction = true;
  				if(lessons.length > 0){
  					if(confirm('提示：复制操作目标周已有课程信息，继续复制将会覆盖掉目标周已有课程，请谨慎操作！')){
  						angular.noop;
  					}else{
  						copyAction = false;
  					}
  				}
  				if(copyAction){
  					var _dataStr = "classType=" + classType + 
			                "&fromWeek=" + fromWeek +
			                "&targetWeek=" + targetWeek;
					httpService.post("lesson/schedule/copy",_dataStr).then(function(rsps){
						alert('复制成功！');
						Utils.setProcessParclose(false);
						console.info('$location',$location);
						//$location.href = "grouplessons/" + targetWeek;
						if(classType===2){
							var actionUrl = '/grouplessons/' + targetWeek +'/2';
							if(actionUrl.indexOf($location.path())>=0){
								$route.reload();
							}else{
								$location.url(actionUrl);
							}
							return;
						}
						
						if(classType===3){
							var actionUrl = '/privatelessons/' + targetWeek + '/3';
							if(actionUrl.indexOf($location.path())>=0){
//								console.error('$route',$route);
								$route.reload();
							}else{
								$location.url(actionUrl);
							}
							return;
						}
						
					},function(rsps){
						console.error("Error",rsps);
				  		alert('复制失败，未知错误');
				  		Utils.setProcessParclose(false);
					});
  				}
  			},function(rsps){
  				console.error("Error",rsps);
		  		alert('复制失败，未知错误');
		  		Utils.setProcessParclose(false);
  			});
  		}else{
  			alert('复制失败，没有可复制的课程');
  			Utils.setProcessParclose(false);
  		}
  	},function(rsps){
  		console.error("Error",rsps);
  		alert('复制失败，未知错误');
  		Utils.setProcessParclose(false);
  	});
  	
  }
  
  
  //TODO 待废除
  function createForm(){
	  Utils.setParclose(true);
	  $scope.page.useCreate=true;
  }
  
  function createLessonForm(){
  	Utils.setParclose(true);
	$scope.page.needCreate=true;
  }
  
  //TODO 待废除
  function unCreateForm(){
	  $scope.page.useCreate=false;
	  Utils.setParclose(false);
	  clearFields();
  }
  
  function unCreateLessonForm(){
  	$scope.page.needCreate=false;
	Utils.setParclose(false);
	clearFields();
  }
  
  
//function editLessonForm(){
//	Utils.setParclose(true);
//	$scope.page.needEdit=true;
//}
//
//function unEditLessonForm(){
//	$scope.page.needEdit=false;
//	Utils.setParclose(false);
//	clearFields();
//}
  
  
  function deleteForm(){
	  Utils.setTopParclose(true);
	  $scope.page.useDelConfirm=true;
  }
  
  
  function unDeleteForm(){
	  $scope.page.useDelConfirm=false;
	  Utils.setTopParclose(false);
  }
  
  function tabSwitch(classTypeV){
	  $scope.classTypeValue=classTypeV;
	  $scope.retrieveCourses(classTypeV);
	  if(classTypeV===2){
		 $scope.tabs[0].active=true;
	  }else{
		 $scope.tabs[1].active=true;
	  }
  }
  

  // get all courses provided by the gym
  function retrieveCourses(classType) {
  	classType = $scope.classType;
	$scope.privateTab = true;
    var _queryCourses = "course/query?classType=" + classType +
                        "&uid=" + $scope.uid; //&classType=2
    var _urlCourses = $scope.apiUrl + _queryCourses;
    httpService.get(_urlCourses).success(function(data) {
      $scope.courses = data;
      //console.log('retrieve all courses: ', $scope.courses);
    });
  }

  //chengwanliu 20150921 more lesson start
  $scope.checkedDays = [];
  $scope.selectDay = function(value,boxchecked){
	  if(boxchecked){
		  $scope.checkedDays.push(value);
	  }else{
		  removeElement($scope.checkedDays,value);
	  }
	  if($scope.log.debug){
		  //console.log("$scope.checkedDaysConcat",$scope.checkedDays.join(","));
	  }
  };
  
  function removeElement(array,element){
	  for(var i=0 ; i< array.length ; i++){
		  if(array[i] === element){
			  array.splice(i,1);
		  }
	  }
  }
  
  function checkClassType(value){
	  $scope.retrieveCourses(value);
  }
  
  var originalLessonTpl;
  function selectTemplate($event,lessonTpl_id){
      var found = $filter('filter')($scope.lessonTpls, { id: lessonTpl_id}, true);
      if (found.length) {
        if (Utils.isUndefinedOrNull($scope.selectedLessonTpl) || $scope.selectedLessonTpl.id !== lessonTpl_id) {
          $scope.selectedLessonTpl = found[0];
          var dayFound = $filter('filter')($scope.dayOfWeek,{value:$scope.selectedLessonTpl.dayOfWeek});
          $scope.selectedLessonTpl.dayOfWeekName = dayFound[0].name;
          originalLessonTpl = angular.extend({},$scope.selectedLessonTpl);
//          originalLessonTpl = angular.copy($scope.selectedLessonTpl);
        } else {
          $scope.selectedLessonTpl = null;
          clearFields();
        } 
      } else {
          //not found
          $scope.selectedLessonTpl = null;
      }
      $event.stopPropagation();
      console.log("$scope.selectedLessonTpl",$scope.selectedLessonTpl);
  }
  
  
  var originalLesson;
  function editLessonForm(lessonId){
  	console.info('editLesson',lessonId);
  	var found = $filter('filter')($scope.lessonTpls, { id: lessonId}, true);
  	if(found.length){
  		found[0].checkAllDay = false;
  		originalLesson = found[0];
  		$scope.selectedLesson = angular.copy(originalLesson);
  		$scope.page.needEdit = true;
  		console.info('$scope.selectedLesson',$scope.selectedLesson);
  	}
  }
  
  
  function unEditLessonForm(){
	$scope.page.needEdit=false;
	Utils.setParclose(false);
	clearFields();
  }
  
  
  //待废除
  function viewLesson_del(lesson){
  	httpService.get("receipt/query?lessonId=" + lesson.id +"&status=5").then(function (resp){
		  $scope.selectedLesson = lesson;
		  $scope.receipts = resp.data;
		  $scope.page.needBookedDetail = true;
	  },function(){
		  alert("查询出错！！！");
		  Utils.setParclose(false);
		  Utils.setProcessParclose(false);
	  });
  }
  
  function unViewLesson(){
  	$scope.page.needBookedDetail = false;
  	Utils.setParclose(false);
  }
  
  
  //TODO chengwanliu more lesson end
  
  // edit on html only
  function editTemplate(){
    $scope.newContract = $scope.selectedLessonTpl.contract; // to be changed
    $scope.newCourse = $scope.selectedLessonTpl.course;
    $scope.newDescription = $scope.selectedLessonTpl.description;
  }

//create new lesson template	TODO 待删除
  function createTemplate() {
	$scope.form.submitted = false;
	var valid = true;
	if(!$scope.lessonTpl.courseId){
		$scope.errMsg.emptyCourse = $scope.msg.emptyCourse;
		valid = false;
	}else{
		$scope.errMsg.emptyCourse = "";
	}
	
	if($scope.checkedDays.length < 1){
		$scope.errMsg.emptyDayofweek = $scope.msg.emptyDayofweek;
		valid = false;
	}else{
		$scope.errMsg.emptyDayofweek = "";
	}
	
	if(!$scope.lessonTpl.numberLimit){
		$scope.errMsg.emptyNumberLimit = $scope.msg.emptyNumberLimit;
		valid = false;
	}else{
		$scope.errMsg.emptyContract = "";
	}
	
	if(!$scope.lessonTpl.contractId){
		$scope.errMsg.emptyContract = $scope.msg.emptyContract;
		valid = false;
	}else{
		$scope.errMsg.emptyContract = "";
	}
	
	var beginH =  $filter('date')($scope.lessonTpl.lessonStart,'HH');
	var beginM =  $filter('date')($scope.lessonTpl.lessonStart,'mm');
	var endH =  $filter('date')($scope.lessonTpl.lessonEnd,'HH');
	var endM =  $filter('date')($scope.lessonTpl.lessonEnd,'mm');
	var endMi = parseInt(endH)*60 + parseInt(endM);
	var beginMi = parseInt(beginH)*60 + parseInt(beginM);
	var duration = endMi - beginMi;
	if(duration < 30){//halfhour
		//alert("结束时间不能小于开始时间");
		$scope.errMsg.endTimeGTBeginTime = $scope.msg.endTimeGTBeginTime;
		valid=false;
	}else{
		$scope.errMsg.endTimeGTBeginTime = "";
	}
	
	$log.info($scope.lessonTpl);
	$log.info($scope.form.$valid && valid);
	if($scope.form.$valid && valid){
		Utils.setProcessParclose(true);
		//var duration = parseInt(($scope.lessonTpl.lessonEnd - $scope.lessonTpl.lessonStart) / 60000);
		var _queryCreateTemplate = "lesson/template/create";
			console.log("$scope.checkedDays.join(",")",$scope.checkedDays.join(","));
		//var beginH =  $filter('date')($scope.lessonTpl.lessonStart,'HH');
		//var beginM =  $filter('date')($scope.lessonTpl.lessonStart,'mm');
		var beginMinute = parseInt(beginH) * 60 + parseInt(beginM);
		var _dataStr = //"?uid=1" + 
			"numberLimit=" + $scope.lessonTpl.numberLimit + 
			"&duration=" + duration +
			"&dayOfWeeks=" + ($scope.checkedDays.join(",")) + 
			"&beginTime=" + beginMinute +
			"&courseId=" + $scope.lessonTpl.courseId +                                          
			"&contractId=" + $scope.lessonTpl.contractId;
			"&memo=" + "";
		var _urlCreateTemplate = $scope.apiUrl + _queryCreateTemplate;
		if($scope.log.debug){
			$log.info("创建%sUrl=>","课程表",_urlCreateTemplate,_dataStr);
		}
		$http ({
			method: 'POST',
			url: _urlCreateTemplate,
			data: _dataStr,
			headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
		}).
		then(function(response) {
			alert("创建课程信息成功");
			$scope.page.useCreate=false;
			Utils.setProcessParclose(false);
			Utils.setParclose(false);
			$scope.retrieveLessonTpls($scope.classTypeValue);
			clearFields();
		}, function(response){
			alert("创建课程信息失败");
		});
	}else{
		$scope.form.submitted = true;
	}
  }
  
  
  function createLesson(){
  	if($scope.classType === '3'){
  		$scope.lessonTpl.lessonStart = $scope.gym.openTime;
  		$scope.lessonTpl.lessonEnd = $scope.gym.closeTime;
  	}
  	var valid = true;
  	if(!$scope.lessonTpl.courseId){
		$scope.errMsg.emptyCourse = $scope.msg.emptyCourse;
		valid = false;
	}else{
		$scope.errMsg.emptyCourse = "";
	}
	
	if($scope.checkedDays.length < 1){
		$scope.errMsg.emptyDayofweek = $scope.msg.emptyDayofweek;
		valid = false;
	}else{
		$scope.errMsg.emptyDayofweek = "";
	}
	
	if(!$scope.lessonTpl.numberLimit){
		$scope.errMsg.emptyNumberLimit = $scope.msg.emptyNumberLimit;
		valid = false;
	}else{
		$scope.errMsg.emptyNumberLimit = "";
	}
	
	if(!$scope.lessonTpl.coachId){
		$scope.errMsg.emptyCoach = $scope.msg.emptyCoach;
		valid = false;
	}else{
		$scope.errMsg.emptyCoach = "";
	}
	
	if(!$scope.lessonTpl.lessonStart){
		$scope.errMsg.emptyLessonStart = $scope.msg.emptyLessonStart;
		valid = false;
	}else{
		$scope.errMsg.emptyLessonStart = "";
	}
	
	if(!$scope.lessonTpl.lessonEnd){
		$scope.errMsg.emptyLessonEnd = $scope.msg.emptyLessonEnd;
		valid = false;
	}else{
		$scope.errMsg.emptyLessonEnd = "";
	}
	
	
	
  	var _createLessonUrl = "lesson/create";
  	var beginMinute = 0;
  	var endMinute = 0;
  	if($scope.lessonTpl.lessonStart && $scope.lessonTpl.lessonEnd){
  		var beginH = $scope.lessonTpl.lessonStart.split(":")[0];
		var beginM = $scope.lessonTpl.lessonStart.split(":")[1];
		var beginMinute = parseInt(beginH) * 60 + parseInt(beginM);
		
		var endH = $scope.lessonTpl.lessonEnd.split(":")[0];
		var endM = $scope.lessonTpl.lessonEnd.split(":")[1];
		var endMinute = parseInt(endH) * 60 + parseInt(endM);
  	}
	var duration = endMinute - beginMinute ;
	
	if(duration <= 0){
		valid = false;
		$scope.errMsg.endLessonTimeGtStartTime = $scope.msg.endLessonTimeGtStartTime;
	}else{
		$scope.errMsg.endLessonTimeGtStartTime = "";
	}
	
	if(!valid){
		return;
	}
	
	var dayOfWeeks = "";
	angular.forEach($scope.checkedDays,function(day){
  	 	dayOfWeeks += "&dayOfWeeks=" + day;
  	 });
	var _dataStr =  "beginMinute=" + beginMinute +
					"&endMinute=" + endMinute +
					"&duration=" + duration + dayOfWeeks +
					"&courseId=" + $scope.lessonTpl.courseId +
					"&numberLimit=" + $scope.lessonTpl.numberLimit +
					"&coachId=" + $scope.lessonTpl.coachId +
					"&week=" + $scope.week +
					"&memo=" + "";
	httpService.post(_createLessonUrl,_dataStr).then(function(rsps){
		var errCode = rsps.data.errCode;
		console.info('rsps',rsps);
		if(errCode==='8000'){
			alert("创建课程信息成功");
		}else if(errCode==='8402'){
			alert("添加失败，时间输入有误！");
		}else if(errCode==='8117'){
			alert("添加失败，没有此课程信息！");
		}else if(errCode==='8111'){
			alert("添加失败，没有此教练或者非绑定的教练！");
		}
		$scope.page.needCreate=false;
		Utils.setProcessParclose(false);
		Utils.setParclose(false);
		$scope.retrieveLessonSchedule($scope.classType);
		clearFields();
	},function(rsps){
		alert("创建课程失败");
		Utils.setProcessParclose(false);
		Utils.setParclose(false);
	});
  }
  
  function updateLesson(classType){
  	//alert($scope.selectedLesson.dayOfWeek);
  	if($scope.classType === '3'){
  		$scope.lessonTpl.lessonStart = $scope.gym.openTime;
  		$scope.lessonTpl.lessonEnd = $scope.gym.closeTime;
  	}
  	var valid = true;
	if(!$scope.selectedLesson.dayOfWeek){
		$scope.errMsg.emptyDayofweek = $scope.msg.emptyDayofweek;
		valid = false;
	}else{
		$scope.errMsg.emptyDayofweek = "";
	}
	
	if(!$scope.selectedLesson.numberLimit){
		$scope.errMsg.emptyNumberLimit = $scope.msg.emptyNumberLimit;
		valid = false;
	}else{
		$scope.errMsg.emptyNumberLimit = "";
	}
	
	if(!$scope.selectedLesson.coach.id){
		$scope.errMsg.emptyCoach = $scope.msg.emptyCoach;
		valid = false;
	}else{
		$scope.errMsg.emptyCoach = "";
	}
	
	if(!$scope.selectedLesson.tBeginDateTime){
		$scope.errMsg.emptyLessonStart = $scope.msg.emptyLessonStart;
		valid = false;
	}else{
		$scope.errMsg.emptyLessonStart = "";
	}
	
	if(!$scope.selectedLesson.tEndDateTime){
		$scope.errMsg.emptyLessonEnd = $scope.msg.emptyLessonEnd;
		valid = false;
	}else{
		$scope.errMsg.emptyLessonEnd = "";
	}
	
  	var _updateLessonUrl = "lesson/update";
  	var week = $routeParams.week;
  	var beginMinute = 0;
  	var endMinute = 0;
  	if($scope.selectedLesson.tBeginDateTime && $scope.selectedLesson.tEndDateTime){
  		var beginH = $scope.selectedLesson.tBeginDateTime.split(":")[0];
		var beginM = $scope.selectedLesson.tBeginDateTime.split(":")[1];
		beginMinute = parseInt(beginH) * 60 + parseInt(beginM);
		
		var endH = $scope.selectedLesson.tEndDateTime.split(":")[0];
		var endM = $scope.selectedLesson.tEndDateTime.split(":")[1];
		endMinute = parseInt(endH) * 60 + parseInt(endM);
  	}
	
	var duration = endMinute - beginMinute ;
	
	if(duration <= 0){
		valid = false;
		$scope.errMsg.endLessonTimeGtStartTime = $scope.msg.endLessonTimeGtStartTime;
	}else{
		$scope.errMsg.endLessonTimeGtStartTime = "";
	}
	
	if($scope.selectedLesson.numberBooked > 0){
		if(
		originalLesson.beginMinute != beginMinute ||
	    originalLesson.endMinute != endMinute ||
	    originalLesson.dayOfWeek != $scope.selectedLesson.dayOfWeek
		){
	     	alert('无法修改课程时间，原因是此课程已有学员预约');
	     	console.info('originalLesson',originalLesson);
	     	$scope.selectedLesson.tBeginDateTime = originalLesson.beginTime;
	     	$scope.selectedLesson.tEndDateTime = originalLesson.endTime;
	     	$scope.selectedLesson.dayOfWeek = originalLesson.dayOfWeek;
	     	return ;
	    }
		
		if(originalLesson.numberLimit > $scope.selectedLesson.numberLimit){
			alert('无法修改上课人数，原因是新修改的上课人数不能少于原来的上课人数');
			$scope.selectedLesson.numberLimit = originalLesson.numberLimit;
			return ;
		}
	}
	
	
	
	console.error('valid',valid);
	if(!valid){
		return ;
	}
	
	var _dataStr =  "id=" + $scope.selectedLesson.id + 
					"&beginMinute=" + beginMinute +
					"&endMinute=" + endMinute +
					"&duration=" + duration +
					"&dayOfWeek=" + $scope.selectedLesson.dayOfWeek +
					"&numberLimit=" + $scope.selectedLesson.numberLimit +
					"&coachId=" + $scope.selectedLesson.coach.id +
					"&week=" + week;
	
	console.info('修改URL:',_updateLessonUrl);
	console.info('修改DataStr:',_dataStr);
	httpService.post(_updateLessonUrl,_dataStr).then(function(rsps){
		var errCode = rsps.data.errCode;
		console.info('rsps',rsps);
		if(errCode==='8000'){
			alert("修改课程信息成功");
		}else if(errCode==='8402'){
			alert("添加失败，时间输入有误！");
		}else if(errCode==='8111'){
			alert("添加失败，没有此教练或者非绑定的教练！");
		}
		$scope.page.needEdit=false;
		Utils.setProcessParclose(false);
		Utils.setParclose(false);
		$scope.retrieveLessonSchedule($scope.classType);
		clearFields();
	},function(rsps){
		alert("修改课程失败");
		Utils.setProcessParclose(false);
		Utils.setParclose(false);
	});
  }
  
  function cancelLessons(){
  	 var classType = $scope.classType;
  	 var ids = [];
  	 var _dataStr = "";
  	 angular.forEach($scope.lessonTpls,function(lesson){
  	 	if(lesson.checked){
  	 		ids.push(lesson.id);
  	 		_dataStr += "&ids="+ lesson.id;
  	 	}
  	 });
  	 if(ids.length > 0){
  	 	if(confirm('确定要取消选中的课程吗？')){
  	 		Utils.setParclose(true);
	  	 	var _queryDeleteTemplate = "lesson/cancel";
	  	 	console.info("_dataStr",_dataStr.substr(1));
	  	 	httpService.post(_queryDeleteTemplate,_dataStr).then(function(rsps){
	  	 		console.info('rsps',rsps);
	  	 		if(true){
	  	 			alert('取消课程成功！');
	  	 			Utils.setParclose(false);
	  	 			retrieveLessonSchedule(classType);
	  	 			$scope.checkedNonPublishLesson=false;
	  	 			$scope.checkedAllLessons=false;
	  	 		}
	  	 	},function(rsps){
	  	 		alert("取消课程出现未知错误");
	  	 		$scope.checkedNonPublishLesson=false;
	  	 		$scope.checkedAllLessons=false;
	  	 		Utils.setParclose(false);
	  	 	});
  	 	}
  	 }else{
  	 	alert('请选择要取消的课程...');
  	 }
  }
  
  
  function checkAllDay(lesson){
  	lesson.checkAllDay = lesson.checkAllDay || false;
  	lesson.checkAllDay = !lesson.checkAllDay;
  	if(lesson.checkAllDay){
  		lesson.lessonStartDisabled = true;
  		lesson.lessonEndDisabled = true;
  		lesson.lessonStart = $scope.gym.openTime || '10:00';
  		lesson.lessonEnd = $scope.gym.closeTime || '22:00';
  		
  		lesson.tBeginDateTime = $scope.gym.openTime || '10:00';
  		lesson.tEndDateTime = $scope.gym.closeTime || '22:00';
  	}else{
  		lesson.lessonStartDisabled = false;
  		lesson.lessonEndDisabled = false;
  	}
  	console.info('lesson.checkAllDay',lesson.checkAllDay);
  }
  
  function  cancelledView(){
	  $scope.selectedLessonTpl = angular.extend($scope.selectedLessonTpl,originalLessonTpl);
	  Utils.setParclose(false);
	  clearFields();
  }
  
  
  function sendLesson(){
  	 var classType = $scope.classType;
  	 var ids = [];
  	 var _dataStr = "";
  	 var statusFailed = false;
  	 angular.forEach($scope.lessonTpls,function(lesson){
  	 	if(lesson.checked){
  	 		if(lesson.status !== 8){
  	 			statusFailed = true;
  	 		}
  	 		ids.push(lesson.id);
  	 		_dataStr += "&ids="+ lesson.id;
  	 	}
  	 });
  	 if(statusFailed){
  	 	alert('已发布的课不能重新发布，请重新选择要发布的课');
  	 	return;
  	 }
  	 if(ids.length > 0){
  	 	Utils.setParclose(true);
  	 	if(confirm('课程发布成功后，学员就能使用手机App（无糖运动）进行约课了，是否确定发课？')){
	  	 	var _querySendUrl = "lesson/send";
	  	 	console.info("_dataStr",_dataStr.substr(1));
	  	 	httpService.post(_querySendUrl,_dataStr).then(function(rsps){
	  	 		//console.info('rsps',rsps);
	  	 		var errCode = rsps.data.errCode;
	  	 		if(errCode==='8000'){
	  	 			alert('课程发布成功！现在学员就可以通过手机App（无糖运动）约课了');
	  	 			Utils.setParclose(false);
	  	 			$scope.checkedNonPublishLesson=false;
	  	 			$scope.checkedAllLessons=false;
	  	 			retrieveLessonSchedule(classType);
	  	 		}
	  	 	},function(rsps){
	  	 		alert("发布课程出现未知错误");
	  	 		Utils.setParclose(false);
	  	 		$scope.checkedNonPublishLesson=false;
	  	 		$scope.checkedAllLessons=false;
	  	 	});
  	  }else{
  	  	Utils.setParclose(false);
  	  }
  	 }else{
  	 	alert('请选择要发布的课程...');
  	 }
  }
  
  function checkNonPublishLessons(status){
  	$scope.checkedAllLessons = false;
  	var number = 0;
  	angular.forEach($scope.lessonTpls,function(lesson){
  		lesson.checked = false;
  	 	if(lesson.status===status){
  	 		lesson.checked = !$scope.checkedNonPublishLesson;
  	 		number ++ ;
  	 	}
  	 });
  	 if(number > 0){
  	 	$scope.checkedNonPublishLesson = !$scope.checkedNonPublishLesson;	
  	 }else{
  	 	alert('没有可选的课程');
  	 	$scope.checkedNonPublishLesson = false;	
  	 }
  }
  
  function checkAllLessons(status){
  	$scope.checkedNonPublishLesson = false;
  	var number = 0;
  	angular.forEach($scope.lessonTpls,function(lesson){
  		lesson.checked = false;
  	 	if(lesson.status===status || status===0){
  	 		lesson.checked = !$scope.checkedAllLessons;
  	 		number ++ ;
  	 	}
  	 	
  	 });
  	 if(number > 0){
  	 	$scope.checkedAllLessons = !$scope.checkedAllLessons;	
  	 }else{
  	 	alert('没有可选的课程');
  	 	$scope.checkedAllLessons = false;	
  	 }
  }
  
  
  function retrieveCourseByPage(){
  	$scope.courseBtnGroup = true;
  	$scope.lessonBtnGroup = false;
  }
  
  function selectAllCourses(classType){
  	$scope.checkedAllCourses = !$scope.checkedAllCourses;
  	angular.forEach($scope.courses,function(course){
  		course.checked = $scope.checkedAllCourses;
  	});
  }
  
  function createCourseForm(){
	Utils.setParclose(true);
	$scope.page.needCourseCreate=true;
  }
  
  function unCreateCourseForm(){
  	$scope.page.needCourseCreate=false;
	Utils.setParclose(false);
	clearFields();
  }
  
  
  var originalLesson;
  function editLessonForm(lessonId){
  	console.info('editLesson',lessonId);
  	var found = $filter('filter')($scope.lessonTpls, { id: lessonId}, true);
  	if(found.length){
  		found[0].checkAllDay = false;
  		originalLesson = found[0];
  		$scope.selectedLesson = angular.copy(originalLesson);
  		$scope.page.needEdit = true;
  		console.info('$scope.selectedLesson',$scope.selectedLesson);
  	}
  }
  
  var originalCourse;
  function editCourseForm(courseId){
  	var found = $filter('filter')($scope.courses, { id: courseId}, true);
  	if(found.length){
  		originalCourse = found[0];
  		$scope.selectedCourse = angular.copy(originalCourse);
  		Utils.setParclose(true);
		$scope.page.needCourseEdit=true;
  		console.info('$scope.selectedCourse',$scope.selectedCourse);
  	}
  }
  
  function unEditCourseForm(){
  	$scope.page.needCourseEdit=false;
	Utils.setParclose(false);
  }
  
  function createCourse() {
  		var classType = $scope.classType;
    	var valid = true;
    	$scope.course = $scope.course || {};
    	if (!$scope.course.sportV) {
    		$scope.errMsg.emptySporttype = $scope.msg.emptySporttype;
            valid = false;
        }else{
            $scope.errMsg.emptySporttype = "";
        }
    	if (typeof($scope.course.priceInt)==='undefined'){
    		$scope.errMsg.emptyPrice = $scope.msg.emptyPrice;
            valid = false;
	    }else{
	    	$scope.errMsg.emptyPrice = "";
	    }
    	
    	if (!$scope.course.title){
    		$scope.errMsg.emptyTitle = $scope.msg.emptyTitle;
            valid = false;
        }else{
        	$scope.errMsg.emptyTitle = "";
        }
    	if(valid){
    		Utils.setProcessParclose(true);
	        var _queryCreateCourse = "course/create";
	        $scope.course.classTypeV = $scope.course.classTypeV || $scope.initVal.classTypeV;
	        var _dataStr = "title=" + $scope.course.title + 
	                "&description=" + (typeof($scope.course.description)==="undefined"?"":$scope.course.description) +
	                "&priceInt="+$scope.course.priceInt +
	        		"&classType="+ classType +
	        		"&sportType="+$scope.course.sportV;
	        
	        var images = $scope.courseAddImages
	        var _imgStr = "";
	        for(var i=0 ; i < $scope.courseAddImages.length ; i++){
	        	_imgStr +="&images=" + $scope.courseAddImages[i].key;
	        }
	        _dataStr += _imgStr;
			
			console.error("_dataStr",_dataStr);
			
	        var _urlCreateCourse = $scope.apiUrl + _queryCreateCourse;
	        
	        if($scope.log.debug){
	        	$log.info("create%sUrl=>",'课程信息',_urlCreateCourse,_dataStr);
	        }
	        httpService.post(_urlCreateCourse,_dataStr).then(function(response) {
	            alert("课程信息保存成功");
	            $scope.course = {};
	            $scope.courseAddImages = [];
	            unCreateCourseForm();
	            Utils.setParclose(false);
	            Utils.setProcessParclose(false);
	            retrieveCourses($scope.initVal.classTypeV);
	          }, function(response){
	            alert("课程信息保存失败");
	            Utils.setParclose(false);
	            Utils.setProcessParclose(false);
	            console.log('create course failed', response.data);
	          });
    	}
   }
  
  function updateCourse() {
      var valid = true;
      if (!$scope.selectedCourse.sport.value){
    	  $scope.errMsg.emptySporttype = $scope.msg.emptySporttype;
    	  valid = false;
      }else{
    	  $scope.errMsg.emptySporttype = "";
      }
      
      if (!$scope.selectedCourse.priceInt) {
    	  console.log($scope.selectedCourse.priceInt);
    	  $scope.errMsg.emptyPrice = $scope.msg.emptyPrice;
    	  valid = false;
      }else{
    	  $scope.errMsg.emptyPrice = "";
	  }
      
      if (!$scope.selectedCourse.title) {
    	  $scope.errMsg.emptyTitle = $scope.msg.emptyTitle;
    	  valid = false;
      }else{
    	  $scope.errMsg.emptyTitle = "";
	  }
      
      if(valid){
    	  Utils.setProcessParclose(true);
    	  var _queryUpdateCourse = "course/edit";
    	  $scope.selectedCourse.classType.value = $scope.selectedCourse.classType.value || $scope.initVal.classTypeV;
    	  var _dataStr = "id=" + $scope.selectedCourse.id + 
    	  "&title=" + $scope.selectedCourse.title + 
    	  "&description=" + $scope.selectedCourse.description +
    	  "&classType=" + $scope.selectedCourse.classType.value +
    	  "&sportType=" + $scope.selectedCourse.sport.value +
    	  "&priceInt=" + $scope.selectedCourse.priceInt;
    	  
    	  var _imgStr = "";
    	  console.error("courseEditImages",$scope.courseEditImages);
    	  for(var i=0 ; i < $scope.courseEditImages.length ; i++){
    	  	_imgStr +="&images=" + $scope.courseEditImages[i].key;
    	  }
    	  var _delImgStr = "";
    	  if($scope.selectedCourse.deletedImages){
    	  	for(var i=0 ; i < $scope.selectedCourse.deletedImages.length ; i++){
    	  		_delImgStr +="&deletedImages=" + $scope.selectedCourse.deletedImages[i];
    	  	}
    	  }
	      _dataStr += _imgStr;
	      _dataStr += _delImgStr;
    	  
    	  var _urlUpdateCourse = $scope.apiUrl + _queryUpdateCourse;
    	  
    	  if($scope.log.debug){
    		  $log.info("修改%s","课程",_urlUpdateCourse,_dataStr);
    	  }
    	  $http ({
    		  method: 'POST',
    		  url: _urlUpdateCourse,
    		  data: _dataStr,
    		  headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
    	  }).
    	  then(function(response) {
    		  if(response.status === 200){
    			  alert("课程信息保存成功");
    			  unEditCourseForm();
    			  $scope.courseEditImages = [];
    			  Utils.setParclose(false);
    			  Utils.setProcessParclose(false);
    			  $scope.retrieveCourses($scope.selectedCourse.classType.value);
    			  $scope.clearFields();
    		  }
    	  }, function(response){
    		  alert("课程信息保存失败");
    		  Utils.setProcessParclose(false);
    	  });
      }
  }
  
  function deleteCourse(){
  	var classType = $routeParams.classType;
  	var ids = [];
  	var _dataStr = "";
  	angular.forEach($scope.courses,function(course){
	 	if(course.checked){
	 		ids.push(course.id);
	 		_dataStr += "&ids="+ course.id;
	 	}
  	});
	
	if(ids.length > 0){
		if(confirm('确定要删除课程信息吗？')){
			Utils.setProcessParclose(true);
			var delCourseUrl = "course/delete";
			$log.info("delete%surl=>","课程信息",delCourseUrl);
			$log.info("delete%_dataStr=>","课程信息",_dataStr);
			httpService.post(delCourseUrl,_dataStr.substr(1)).then(function(rsps){
				var errCode = rsps.data.errCode;
				if(errCode === "8000"){
					alert("删除课程成功！！！");
					 Utils.setProcessParclose(false);
				}else{
					alert("删除课程失败！！！");
				}
			    $scope.retrieveCourses(classType);
			    $scope.page.useEdit=false;
			},function(){
				alert("删除课程出现未知错误");
				Utils.setProcessParclose(false);
			});
		}
	}else{
		alert("请选择要删除的课程信息");
	}
  }
  
    function delCourseImage(fileId,type){
    	console.error(fileId,type);
    	if(type === 'Add'){
    		delCourseAddImage(fileId);
    	}else{
    		delCourseEditImage(fileId);
    	}
    }
    
    function delCourseAddImage(fileId){
	  	$scope.courseAddImages = removeElementInArray($scope.courseAddImages,fileId);
    }
    
    function delCourseEditImage(fileId){
	  	$scope.courseEditImages = removeElementInArray($scope.courseEditImages,fileId);
    }
    
    function removeElementInArray(array,fileId){
    	console.info("fileId:",array.length);
    	var _array = [];
    	for(var i = 0; i< array.length ; i++){
    		console.info(i+":",array[i]);
    		if(array[i]['id'] !== fileId){
    			_array.push(array[i]);
    		}
    	}
    	return _array;
    }
    
   function delOriginCourseImage(index,fileId){
		$scope.selectedCourse.images.splice(index, 1);
		$scope.selectedCourse.deletedImages = $scope.selectedCourse.deletedImages || [];
		$scope.selectedCourse.deletedImages.push(fileId);
   }
   
   	function viewLesson(lesson){
		var options = {
			expandParams:{
				lessonId:lesson.id	
			},
			getDataFn:function(params){
				var lessonId = params.lessonId;
	  			var page = params.page();
	  			var count = params.count();
	  			var _url = "receipt/query?isPage=1&page=" + page + "&limit="+ count +"&lessonId=" + lessonId +"&status=5";
		  		return httpService.get(_url);
			},
			procResult:function(data){
				angular.forEach(data.list, function(item) {
					item.time = timeService.patten(item.time);
			    });
				return data;
			}
		};
		$scope.tableParamsReceipt = pageService.getTableParams(options);
		angular.extend($scope.tableParamsReceipt.$params,{nowdate:new Date()});
		$scope.tableParamsReceipt.reload();
		$scope.selectedLesson = lesson;
		$scope.page.needBookedDetail = true;
	}
   	
    
    
  
  
  function clearFields(){
	  $scope.lessonTpl = {};
	  $scope.selectedLesson = {};
	  $scope.course = {};
	  $scope.selectedCourse = {};
	  $scope.checkedDays = [];
	  angular.forEach($scope.dayOfWeek,function(day){
		  day.checked = false;
	  });
  }
  
  
 function initData(){
 		
 		var urlParams = $location.path().substr(-3);
 		var week = urlParams.substr(0,1);
 		var classType = urlParams.substr(-1);
// 		console.info('route.current.params',$location.path().substr(-3));
// 		console.info('weekweekweekweek',week);
 		$scope.classType = classType;
 		$scope.week = week;
 		
	    $scope.dayOfWeek = [
	                        {"value": 2, "name": "星期一","date":timeService.getDateByWeekAndDayOfWeek(week,1),"checked":false},
	                        {"value": 3, "name": "星期二","date":timeService.getDateByWeekAndDayOfWeek(week,2),"checked":false},
	                        {"value": 4, "name": "星期三","date":timeService.getDateByWeekAndDayOfWeek(week,3),"checked":false},
	                        {"value": 5, "name": "星期四","date":timeService.getDateByWeekAndDayOfWeek(week,4),"checked":false},
	                        {"value": 6, "name": "星期五","date":timeService.getDateByWeekAndDayOfWeek(week,5),"checked":false},
	                        {"value": 7, "name": "星期六","date":timeService.getDateByWeekAndDayOfWeek(week,6),"checked":false},
	                        {"value": 1, "name": "星期日","date":timeService.getDateByWeekAndDayOfWeek(week,7),"checked":false}
	    ];
	    
	    dicSerivce.getCoachs().success(function(data){
	    	$scope.coachs = data;
	    });
	    
	    dicSerivce.getSports(classType).success(function(data){
			$scope.sports = data;
			//console.info('$scope.sports',$scope.sports);
		});
		
		dicSerivce.getPrices(classType).success(function(data){
        	  $scope.prices = data;
  	          angular.forEach($scope.prices, function(price){
  	        	  price.priceText = " X " + price.price;
  	          });
  		});
  		
  		dicSerivce.getGym().success(function(data){
  			  //console.info('data',data);
        	  $scope.gym = data;
  		});
  		
	    
	    retrieveCourses();
	    $scope.TIME_GROUP = TIME_GROUP;
	    
	    $scope.lessonTpl = $scope.lessonTpl || {};
	    $scope.lessonTpl.checkAllDay = false;
	    
	    $scope.classTypes = ClassTypes;
	    $scope.classTypeValue=2;
	    
	    //2015.10.11
	    $scope.page = {
			useCreate:false,
			useEdit:false,
			useDelConfirm:false,
			useOffEditConfirm:false,
			needCreate:false,
			needEdit:false,
			needBookedDetail:false,
			needCourseCreate:false,
			needCourseEdit:false,
			needSignForm:false
	 	};
	    
	    //default value
	    $scope.initVal = {
	 		classTypeV : 2
	 	};
	    
	    $scope.msg={
	 			emptyDayofweek:"错误：请选择星期",
	 			emptyCoach:"错误：请选择代课教练",
	 			emptyNumberLimit:"错误：上课人数不能为空",
	 			emptyCourse:"错误：请选择待发布的课程",
	 			emptyLessonStart:"错误：课程开始时间不能为空",
				emptyLessonEnd:"错误：课程结束时间不能为空",
				emptySporttype:"错误：请选择课程项目",
    			emptyPrice:"错误：请选择价格",
    			emptyTitle:"错误：请填写课程名称",
    			emptyClassType:"错误：请选择课程类型",
				endLessonTimeGtStartTime:"错误：课程的结束时间不能大于开始时间",
	 			endTimeGTBeginTime:"错误：结束时间至少大于开始时间30分钟",
	 			emptySign:"错误：签到码为空",
				invalidSign:"错误：无效的签到码"
				
	 	};
	 	$scope.errMsg = {};
	 	
	 	var subHeader = "基础课";
	 	if(classType==='3'){
	 		subHeader = "私教课";
	 	}
	 	$scope.tabs = [{header:"课表（" + timeService.getDateByWeekAndDayOfWeek(week,1) + 
	 							"~" + timeService.getDateByWeekAndDayOfWeek(week,7) + "）"},
	 					{header:"课程管理-" + subHeader}];
	 	
	 	$scope.qiniuDomain = QINIU.domain;
    	$scope.courseAddImages = [];
    	$scope.courseEditImages = [];
	 	
	 	//debug
	 	$scope.log={
	 		debug:true
	 	};
 }
 initData();
}]);